# -*- coding: utf-8 -*-

import logging
import logging.handlers

import os
from tornado import ioloop
import tornado.httpserver
import tornado.web

__author__ = 'Ennis'

from common.http_serv import app
from common.settings import log_level, HTTP_PORT
import server


def init_logging():
    """
    日志文件设置
    """
    if not os.path.exists("log"):
        os.makedirs("log")
    logger = logging.getLogger()
    logger.setLevel(log_level)

    sh = logging.StreamHandler()
    file_log = logging.handlers.TimedRotatingFileHandler('log/server.log', 'MIDNIGHT', 1, 15)
    formatter = logging.Formatter(
        '[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
    sh.setFormatter(formatter)
    file_log.setFormatter(formatter)

    logger.addHandler(sh)
    logger.addHandler(file_log)

    logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))


if __name__ == '__main__':
    try:
        # 日志初始化
        init_logging()
        # 初始化Server
        http_server = tornado.httpserver.HTTPServer(app)  # http
        logging.info("start sever at port:%s", HTTP_PORT)
        http_server.listen(HTTP_PORT)
        tornado.ioloop.IOLoop.instance().start()

    except Exception as err:
        log_str = 'server start fail! err = %s' % err
        logging.fatal(log_str)
